import 'dart:io';
import 'package:dio/dio.dart';
import 'package:honeypotflutter/net/public_httpInfo.dart';
import 'package:honeypotflutter/net/public_httpResult.dart';
import 'package:honeypotflutter/publicBussine/loginInfo/bussine_loginExit.dart';
import 'package:honeypotflutter/public/public_alert.dart';

class HttpInterceptor extends InterceptorsWrapper {
  /*
  * 请求拦截器
  * */
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (MGHttpInfo.token.isNotEmpty) {
      options.headers["Authorization"] = "Bearer ${MGHttpInfo.token}";
    }
    options.contentType = "application/json; charset=utf-8";
    return handler.next(options);
  }

  /*
  * 响应拦截器
  * */
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.statusCode == 200) {
      HttpResult result = HttpResult.fromJson(response.data);
      response.data = result;
      handler.resolve(response);
      return;
    }
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    print("error ==== ${err}");

    /// token失效情况处理
    // TODO: 401待处理
    if (err.response?.data != null) {
      int code = err.hashCode;
      if (err.response!.statusCode != null) {
        code = err.response!.statusCode!;
      }
      if (code == 401) {
        tokenLoseAction();
        return;
      }
      HttpResult error = HttpResult.fromJson(err.response!.data);
      handler.next(DioException(requestOptions: err.requestOptions, error: error.error));
    } else {
      HttpErrorResult error = HttpErrorResult.fromJson({"code": err.error.hashCode, "details": "网络错误,稍后重试！", "message": "网络错误"});
      handler.next(DioException(requestOptions: err.requestOptions, error: error));
    }
  }

  /*
  * token 失效
  * */
  void tokenLoseAction() async {
    HLAlert.showSureCancelAlert(
      title: "登录失效",
      message: "去重新登录",
      sureAction: (bool isOk) {
        if (isOk) {
          LoginExit.quit();
        } else {
          exit(0);
        }
      },
    );
  }
}
